<template>
    <div class="app-container">
      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" :visible.sync="UploadOpen" width="500px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".jpg, .png, .xlsx, .xls, .pdf, .txt, .doc"
          :action="upload.url"
          :headers="upload.headers"
          :file-list="upload.fileList"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading" @click="submitUpload">上传到服务器</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
<!--          <el-button type="primary" @click="submitForm">确 定</el-button>-->
          <el-button @click="cancel">关闭</el-button>
        </div>
      </el-dialog>
      <el-button type="primary" @click="saveReport">保存</el-button>
      <el-table v-loading="loading" highlight-current-row :data="list" border
                :cell-class-name="tableRowClassName" @cell-click="handleCellClick"  :header-cell-style="handerMethod"  :span-method="objectSpanMethod">
        <el-table-column label="工序名称" align="center" prop="processName" width="80px" />
        <el-table-column label="信息项" align="center" prop="infoItem" width="120px" />
        <el-table-column label="单位" align="center" prop="unit" />


        <el-table-column label="1月" align="center" prop="month1">
          <template slot-scope="scope">
            <el-input v-model="scope.row.month1" v-if="scope.row.material == 1"  size="min" :controls="false" @input="(v)=>(scope.row.month1=handleInput(v)  )"
                      :id="'id' + scope.row.index + scope.column.index" class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month1 }}</p>
            </div>
          </template>
        </el-table-column>



          <el-table-column label="2月" align="center" prop="month2">
            <template slot-scope="scope">
              <el-input  v-if="scope.row.material == 1"  v-model="scope.row.month2" size="min" :controls="false"  @input="(v)=>(scope.row.month2=handleInput(v)  )"
                         :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%"/>
              <div v-else>
                <p >{{ scope.row.month2 }}</p>
              </div>
            </template>
          </el-table-column>
        <el-table-column label="3月" align="center" prop="month3">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month3" size="min" :controls="false"  @input="(v)=>(scope.row.month3=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month3 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="4月" align="center" prop="month4">
          <template slot-scope="scope">
            <el-input  v-if="scope.row.material == 1" v-model="scope.row.month4" size="min" :controls="false"  @input="(v)=>(scope.row.month4=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month4 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="5月" align="center" prop="month5">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month5" size="min" :controls="false"  @input="(v)=>(scope.row.month5=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month5 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="6月" align="center" prop="month6">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month6" size="min" :controls="false"  @input="(v)=>(scope.row.month6=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month6 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="7月" align="center" prop="month7">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month7" size="min" :controls="false"  @input="(v)=>(scope.row.month7=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month7 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="8月" align="center" prop="month8">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month8" size="min" :controls="false"  @input="(v)=>(scope.row.month8=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month8 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="9月" align="center" prop="month9">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month9" size="min" :controls="false"  @input="(v)=>(scope.row.month9=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month9 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="10月" align="center" prop="month10">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month10" size="min" :controls="false"  @input="(v)=>(scope.row.month10=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month10 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="11月" align="center" prop="month11">
          <template slot-scope="scope">
            <el-input v-if="scope.row.material == 1"  v-model="scope.row.month11" size="min" :controls="false"  @input="(v)=>(scope.row.month11=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month11 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="12月" align="center" prop="month12">
          <template slot-scope="scope">
            <el-input  v-if="scope.row.material == 1" v-model="scope.row.month12" size="min" :controls="false"  @input="(v)=>(scope.row.month12=handleInput(v)  )"
                       :id="'id' + scope.row.index + scope.column.index"   class="input-color" style="width: 100%;"/>
            <div v-else>
              <p >{{ scope.row.month12 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="全年" align="center" prop="yearValue"/>
        <el-table-column label="获取方式" align="center" prop="getWay" />
        <el-table-column label="来源" align="center" prop="source" />
        <el-table-column label="支撑材料" align="center" prop="material">
          <template slot-scope="scope">
            <el-button style="margin-left: 10px;" size="small" type="success" v-if="scope.row.material"  @click="handleUpload(scope.row)">上传附件</el-button>
          </template>
        </el-table-column>
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">-->
<!--          <template slot-scope="scope">-->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              icon="el-icon-plus"-->
<!--              @click="handlekeyOUpdate(scope.row)"-->
<!--            >保存-->
<!--            </el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
    </div>
  </template>

  <script>
  import {
    updateAssist, listAssist, updateAssistList
  } from '@/api/app/carbonEmission/assist'
    import { getToken } from "@/utils/auth";
    import {updateEquip} from "@/api/app/carbonEmission/equip";
  import {addUploadInfo} from "@/api/app/carbonEmission/uploadInfo";

    export default {
      name: "assist",
      data() {
        return {
          loading: false,
          total: 0,
          list: [],
          // 查询参数
          queryParams: {
            year: '2025',
          },
          tab3Name: null,
          plcCacheList: [],
            dateRange: [this.moment().subtract('hours', 1).format('YYYY-MM-DD HH:mm:ss'), this.moment().format('YYYY-MM-DD HH:mm:ss')],
        //上传参数
          // 上传参数
          upload: {
            // 是否禁用上传
            isUploading: false,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/common/upload",
            // 上传的文件列表
            fileList: []
          },
          uploadInfo:{
            belong:'辅助报表',
            itemInfo:'',
            filePath:'',
            fileNameReal:'',
            fileNameShow:'',
            fileSize:'',
            delFlag:''
          },
          curRow:{

          },
          UploadOpen:false,
          title:'上传文件信息',
          form:{
            file:'',

          },
          rules:{

          },
        }
      },
      created() {
        this.getList()
      },
      methods: {
        getList() {

            listAssist(this.queryParams).then(res => {
            this.list = res.data.rows
            this.total = res.data.total
                this.getSpanArr(this.list)
            this.loading = false
          })
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1
          this.getList()
        },
        tableRowClassName({row, column, rowIndex, columnIndex}) {
          this.maxColumnIndex = columnIndex   //获取表格的列数
          row.index = rowIndex
          column.index = columnIndex
        },
        handleCellClick(row, column) {
          let activeElement = document.activeElement.nodeName.toLocaleLowerCase()  //当前获取焦点的元素
          //只有Input才有焦点事件
          if (activeElement == 'input') {
            //当前获取焦点的元素，属于表格的第几行的第几个元素
            this.currentClickEl = {
              rowIndex: row.index,
              columnIndex: column.index
            }
            this.keyDown()
          } else {
            this.currentClickEl = null
          }
        },
        //添加键盘事件  得到上下左右键的点击；取消tab键的默认行为
        keyDown() {
          let that = this;
          document.onkeydown = (e) => {
            let el = e || e.event || window.enevt || arguments.callee.callee.arguments[0];
            if (!that.currentClickEl) return
            console.log(el.key)
            //上键
            if (el && el.key == 'ArrowUp') {
              that.getIdByIndex('row', -1)
            }
            //下
            if (el && el.key == 'ArrowDown') {
              that.getIdByIndex('row', 1)
            }
            //左
            if (el && el.key == 'ArrowLeft') {
              that.getIdByIndex('column', -1)
            }
            //右
            if (el && el.key == 'ArrowRight') {
              that.getIdByIndex('column', 1)
            }
            if (el && el.key == 'Tab') {
              el.preventDefault();   //阻止默认行为
            }
          }
        },
        //判断：上键的时候：行的Index减1，到0停止
//判断：上键的时候：行的Index减1，到0停止
//判断：下键的时候：行的Index加1，到表格的最后一行停止；表格的最后一行取决于表格数据的数组
//判断：左键的时候：列的index减1，到index=0停止
//判断：右键的时候：列的index加1，到表格的最大列数停止
//给input框赋值动态id，获取到这个id；给这个元素获取焦点
//判断：当前的元素是不是input框，表格里面判断是不是都是输入框，不是的时候跳到下一个输入框
        getIdByIndex(type, num) {
          let that = this;

          if (this.tab2Name == 'productData') {
            if (type == 'row') {
              if (num > 0 && that.currentClickEl.rowIndex == that.list.length - 1) return
              if (num < 0 && that.currentClickEl.rowIndex == 0) return
              that.currentClickEl.rowIndex = Number(that.currentClickEl.rowIndex) + num
            } else {
              if (num < 0 && that.currentClickEl.columnIndex == 0) {
                that.currentClickEl.columnIndex = 1
                return
              }
              if (num > 0 && that.currentClickEl.columnIndex == that.maxColumnIndex) return
              that.currentClickEl.columnIndex = Number(that.currentClickEl.columnIndex) + num
            }
            let newId = 'id' + String(that.currentClickEl.rowIndex) + that.currentClickEl.columnIndex
            if (!document.getElementById(newId)) {
              that.getIdByIndex(type, num)
              return
            }
            if (!newId) return
            document.getElementById(newId).focus()
          }
          if (this.tab3Name == 'assist') {
            if (type == 'row') {
              if (num > 0 && that.currentClickEl.rowIndex == that.list.length - 1) return
              if (num < 0 && that.currentClickEl.rowIndex == 0) return
              that.currentClickEl.rowIndex = Number(that.currentClickEl.rowIndex) + num
            } else {
              if (num < 0 && that.currentClickEl.columnIndex == 0) {
                that.currentClickEl.columnIndex = 1
                return
              }
              if (num > 0 && that.currentClickEl.columnIndex == that.maxColumnIndex) return
              that.currentClickEl.columnIndex = Number(that.currentClickEl.columnIndex) + num
            }
            let newId = 'idT' + String(that.currentClickEl.rowIndex) + that.currentClickEl.columnIndex
            if (!document.getElementById(newId)) {
              that.getIdByIndex(type, num)
              return
            }
            if (!newId) return
            document.getElementById(newId).focus()
          }


        },
        handleInput(value) {
          // 使用正则表达式匹配数字和小数点
          let out =''
          const regex = /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
          // 如果输入值不符合正则表达式，则将其设置为上一个有效值
          if (!regex.test(value)) {
            return out
          }else{
            return  value
          }
        },
        handlekeyOUpdate(row) {
          updateAssist(row).then(res => {
            this.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        },

        saveReport(){
          console.log("list "+this.list);
          updateAssistList(this.list).then(res => {
            this.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        },
        /** 本地地提交信息 */
        submitForm() {
          //后台处理
          console.log("2  this.upload.fileList"+this.upload.fileList);
          // this.$refs["form"].validate(valid => {
          //   if (valid) {
          //     if (this.form.id != null) {
          //       updateBook(this.form).then(response => {
          //         this.$modal.msgSuccess("修改成功");
          //         this.open = false;
          //         this.getList();
          //       });
          //     } else {
          //       addBook(this.form).then(response => {
          //         this.$modal.msgSuccess("新增成功");
          //         this.open = false;
          //         this.getList();
          //       });
          //     }
          //   }
          // });
          this.UploadOpen = false;
        },
        handleAdd() {

          this.upload.fileList = [];
        },

        handleUpdate(row) {

          this.upload.fileList = [{ name: this.form.fileName, url: this.form.filePath }];
        },
        // 文件提交处理
        submitUpload() {
          this.$refs.upload.submit();
          //后台处理
          console.log("this.upload.fileList"+this.upload.fileList);
        },
// 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
        },
// 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
          this.upload.isUploading = false;
          this.form.filePath = response.url;
          this.msgSuccess(response.msg);
          //可以提交后台
          this.uploadInfo.filePath = fileList[0].response.data.fileName;
          this.uploadInfo.fileSize = fileList[0].size;
          this.uploadInfo.fileNameReal = fileList[0].name
          this.uploadInfo.itemInfo = this.curRow.infoItem
          addUploadInfo(this.uploadInfo).then(res => {
            // this.msgSuccess('提交成功');
          })
        },
        cancel(){
          this.UploadOpen = false;
        },
        handleUpload(row){
          //row 表示当前正要上传文件的行
          console.log("上传文件得信息项为："+row.infoItem)
          this.curRow = row
          this.UploadOpen = true;
        },
          handerMethod({ row, column, rowIndex, columnIndex }) {
              // console.log(row, column, rowIndex, columnIndex)
              // if (rowIndex === 0) {//行索引为0代表表头那一行
              //   if (columnIndex === 1) {//列索引，找到你自己要合并的那一列，这个是动态的，根据实际需求来
              //     this.$nextTick(() => {
              //       if (document.getElementsByClassName(column.id).length !== 0) {
              //         document.getElementsByClassName(column.id)[0].setAttribute('colSpan', 2)
              //       }
              //     })
              //   }
              // }
              // if (rowIndex === 0 && columnIndex ===2) {//将相邻的列设为隐藏
              //   return { display: 'none' }
              // }
              return { background: '#b1defd', color: '#606266', fontWeight: '800', textAlign: 'center' }
          },
          getSpanArr(data) {
              this.spanArr = [];
              this.pos = 0;
              for (let i = 0; i < data.length; i++) {
                  if (i === 0) {
                      this.spanArr.push(1);
                      this.pos = 0;
                  } else {
                      if (data[i].processName === data[i - 1].processName) {
                          this.spanArr[this.pos] += 1;
                          this.spanArr.push(0);
                      } else {
                          this.spanArr.push(1);
                          this.pos = i;
                      }
                  }
              }
          },
          // 合并单元格
          objectSpanMethod({ row, column, rowIndex, columnIndex }) {
              if ([0].includes(columnIndex)) {
                  const _row = this.spanArr[rowIndex];
                  const _col = _row > 0 ? 1 : 0;
                  return {
                      rowspan: _row,
                      colspan: _col
                  }
              }

          }

      }
    };
  </script>
  <style lang="scss" scoped>
     .el-form-item {
      margin-bottom: 10px;
    }
     .input-color {
       ::v-deep {
         .el-input__inner {
           background-color: #ffa200;
           color: #ffffff;
           padding: 0;
           text-align: center;
         }
         .el-textarea__inner {
           background-color: #ffa200;
           color: #ffffff;
           padding: 0;
           text-align: center;
         }

         ::placeholder {
           color: #dddddd;
         }
       }
     }


     ::v-deep .el-table__cell {
       padding: 0 0;

       .cell {
         padding:  0 0;
       }
     }

     .el-table {
       ::v-deep.cell {
         padding: 0;

         .cell {
           padding: 0;
         }
       }
     }

  </style>
